package com.janj.Demo01;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//实现转账的操作
public class Demo1 {
    public static void main(String[] args) {
        //准备数据
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql:///duod9";
        String username = "root";
        String password = "root";
        String sql1 = "UPDATE account SET money = money - 100 WHERE id = ? ";
        String sql2 = "UPDATE account SET money = money + 100 WHERE id = ? ";
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        //------------------
        try {
            //1.获取到连接对象
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);

            //2.开启事务
            conn.setAutoCommit(false);

            //3.获取到执行者,存在两个
             ps1 = conn.prepareStatement(sql1);
             ps2 = conn.prepareStatement(sql2);

            //4.执行SQL语句
            ps1.setInt(1, 1);
            ps2.setInt(1, 2);
            int lineNumber1 = ps1.executeUpdate();
            int lineNumber2 = ps2.executeUpdate();

            //5.处理结果
            String message = (lineNumber1 > 0) && (lineNumber2 > 0) ? "转账成功" : "转账失败";
            System.out.println(message);

            //6.提交事务
            conn.commit();

        } catch (Exception e) {
            //回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                    System.out.println("转账失败111");
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }

        } finally {
            //释放资源
            if (ps1 != null){
                try {
                    ps1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (ps2 != null){
                try {
                    ps2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
